<?php
if (!empty($_POST['fileDetails'])) {
	echo 'message=File Details JSON received as: '.$_POST['fileDetails'];	
}
// delete files older than 600 seconds
$diff = 600;

if ($handle = opendir('uploaded')) {
	while (false !== ($dir = readdir($handle))) {
		if (is_dir('uploaded/'.$dir) && $dir != '..' && $dir != '.') {
			$new = mktime()-filectime('uploaded/'.$dir);
			if ((mktime()-filectime('uploaded/'.$dir)) > 600) {
				remove_dir('uploaded/'.$dir);
			}
		}
	}
}

$return = array();
$uploadfile_fieldname = 'uploadfile';
if (!isset($_FILES[$uploadfile_fieldname])) exit;
    
if ($_FILES[$uploadfile_fieldname]["error"] > 0) {
    $return['status'] = 'ERROR';
    $return['msg'] = "Error: return code: " . $_FILES[$uploadfile_fieldname]["error"];
}
else {
    $filename = $_FILES[$uploadfile_fieldname]["name"];
    /*
    $exts = split("[/\\.]", $filename);
    if (count($exts) > 0) {
        $ext = $exts[count($exts)-1];
        if (strtolower($ext) != "jpg") {
            $return['status'] = 'ERROR';
        	$return['msg'] = "Error: Only JPG files are allowed for upload";
        	
        	echo json_encode($return);
           	exit;
        }
    }
    else 
        exit;
	*/
    $uploadfolder = "uploaded/".md5($filename);
    if (!file_exists($uploadfolder)) {
        if(!@mkdir($uploadfolder)) {
            $return['status'] = 'ERROR';
        	$return['msg'] = 'Could not create ' . $uploadfolder . ' folder';
        }
    }
    $filename = preg_replace('/[\\/\\\\]/m', '_', $filename);
    if (file_exists($uploadfolder . "/" . $filename)) {
    	$return['status'] = 'SUCCESS';
        $return['msg'] = $filename . ' already exists.';
        $return['location'] = "http://www.childdisabilityconnection.org/admin/download.php?file=".$filename;
        $return['filename'] = $filename;
    }
    else {
    	move_uploaded_file($_FILES[$uploadfile_fieldname]["tmp_name"], $uploadfolder . "/" . $filename);
      	
    	$return['status'] = 'SUCCESS';
        $return['msg'] = 'File uploaded.';
        $return['location'] = "http://www.childdisabilityconnection.org/admin/download.php?file=".$filename;
        $return['filename'] = $filename;
    }
}

echo json_encode($return);
exit;

function remove_dir($dir) {
    if(is_dir($dir)) {
        $dir = (substr($dir, -1) != "/")? $dir."/":$dir;
        $openDir = opendir($dir);
        while($file = readdir($openDir)) {
            if(!in_array($file, array(".", ".."))) {
                if(!is_dir($dir.$file))
                    @unlink($dir.$file);
                else
                    remove_dir($dir.$file);
            }
        }
        closedir($openDir);
        @rmdir($dir);
    }
}
?>

